package cn.lyq.card.ui.share


import android.view.View
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.ShareImageInfo
import cn.lyq.card.data.src.Result
import cn.lyq.card.data.src.Status
import cn.lyq.card.utils.RotateYPageTransformer
import cn.lyq.card.utils.loadUrl
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.util.ToastUtils
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import kotlinx.android.synthetic.main.act_share_list.*
import kotlinx.android.synthetic.main.layout_title.*

class ShareListActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(ShareImgVM::class.java)
    }
    private val imgSrcList = mutableListOf<ShareImageInfo>()

    override fun getLayoutId(): Int {
        return R.layout.act_share_list
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_invite_agent)
        tvTitleSplit.visibility = View.GONE
    }

    private fun setBanner() {
        banner.addBannerLifecycleObserver(this).adapter =
            object : BannerImageAdapter<ShareImageInfo>(imgSrcList) {
                override fun onBindView(
                    holder: BannerImageHolder?,
                    data: ShareImageInfo?,
                    position: Int,
                    size: Int
                ) {
                    holder?.imageView?.loadUrl(data?.image)
                }
            }
        banner.setBannerGalleryEffect(40, 40, 10, 0.8f)
        banner.addPageTransformer(RotateYPageTransformer())
        banner.isAutoLoop(false)
    }

    override fun initListener() {
        super.initListener()

        tvConfirm.setClick {
            ShareImgActivity.start(this, imgSrcList[banner.currentItem - 1])
        }
    }

    override fun initObserver() {
        super.initObserver()
        mModel.getData().observe(this, Observer {
            when (it?.status) {
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.toString())
                    dismissLoading()
                }
                Status.SUCCESS -> loadSuccess(it)
                Status.LOADING -> showLoading()
            }
        })
    }

    private fun loadSuccess(it: Result<MutableList<ShareImageInfo>>) {
        imgSrcList.clear()
        imgSrcList.addAll(it.requireData())
        setBanner()
        dismissLoading()
    }
}